﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Contracts;
using System.ServiceModel;

namespace WcfContrib.Showcase.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            IService channel = GetChannel();

            while (true)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Press any key to make a call to the service, 'Enter' to exit'");

                if (Console.ReadKey().Key == ConsoleKey.Enter)
                {
                    break;
                }

                try
                {
                    TestClientCall(channel);

                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("Service was called successfully");
                }
                catch (Exception ex)
                {
                    channel = GetChannel();

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Error: " + ex.ToString());
                }
            }

            CloseChannel(channel);
        }

        static void TestClientCall(IService channel)
        {
            channel.Do(2, new Foo { Id = 1, Name = "Some Foo" });
        }

        #region Channel Helpers
        static IService GetChannel()
        {
            ChannelFactory<IService> factory = new ChannelFactory<IService>("ServiceEP");

            return factory.CreateChannel();
        }

        static void CloseChannel(IService channel)
        {
            ((ICommunicationObject)channel).Close();
        }
        #endregion
    }
}
